import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'
import * as UserApi from '@/api/user'

import { ACCESS_TOKEN, USER_INFO, LOGIN_TIME } from '@/store/mutation-types'

// 登陆成功后执行
const loginSuccess = (commit, result) => {
  const { token, user } = result
  const LoginTime = Date.now()
  // 过期时间30天
  const expiryTime = 43200
  // 保存tokne和userId到缓存
  storage.set(ACCESS_TOKEN, token, expiryTime)
  storage.set(USER_INFO, user, expiryTime)
  storage.set(LOGIN_TIME, LoginTime)

  // 记录到store全局变量
  commit('SET_TOKEN', token)
  commit('SET_USER', user)
}

export const state = {
  // 用户认证token
  token: '',
  // 用户信息
  userInfo: null,
  // 是否登录
  isLogin: !!storage.get(ACCESS_TOKEN)
}

export const mutations = {
  SET_TOKEN: (state, value) => {
    if (value === '') {
      state.isLogin = false
      store.remove(ACCESS_TOKEN)
    } else {
      state.isLogin = true
      state.token = value
    }
  },
  SET_USER: (state, value) => {
    state.userInfo = value
  }
}

export const actions = {
  // 用户登录(普通登录: 输入账号、密码)
  Login({ commit }, data) {
    return new Promise((resolve, reject) => {
      LoginApi.getLogin(data, { custom: { catch: true } })
        .then((response) => {
          loginSuccess(commit, response?.result)
          resolve(response)
        })
        .catch(reject)
    })
  },

  // 用户信息
  Info({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.userInfo) {
        return resolve(state.userInfo)
      }
      UserApi.getInfo()
        .then((response) => {
          const result = response
          commit('SET_USER', result)
          resolve(response)
        })
        .catch(reject)
    })
  },

  // 退出登录
  Logout({ commit }, data) {
    return new Promise((resolve, reject) => {
      LoginApi.logout(data, { custom: { catch: true } })
        .then((response) => {
          storage.remove(ACCESS_TOKEN)
          commit('SET_TOKEN', '')
          resolve(response)
        })
        .catch(reject)
    })
  }
}
